# coding=utf-8

from mysql import UsingMysql
import re

class Diseaseimg_Model:
    '''
    Google-丁香疾病图片数据库
    disease Model
    @author spring
    @date 2022.02.24
    '''

    # 序号
    id = 0

    did = 0

    name = ''

    title = ''

    url = ''

    base = ''

    index = 0

    #表名
    __table_name = 'ai_google_disease_imgs'


    def __init__(self, did, name, title, url, base, index):

        """
        初始化
        """
        self.did = did
        self.name = name
        self.title = title
        self.url = url
        self.base = base
        self.index = index

    #def __str__(self) -> str:
        #return self.serial_id + ',' + self.pharmacy_name + ',' + self.pilot_area

    def save(self):
        """
        保存
        """
        data = self.get(str(self.id))
        if data:
            self.update()
        else:
            self.insert()    

    def insert(self):
        """
        新增文章
        """
        with UsingMysql(log_time=True) as um:

            sql = (
                "INSERT INTO `"+self.__table_name +"` (`did`,`name`,`title`,`url`,`base`,`index`) "
                "VALUES(%s,%s,%s,%s,%s,%s)"
            )
            sql = sql % (um._conn.escape(self.did),
                         um._conn.escape(self.name),
                         um._conn.escape(self.title),
                         um._conn.escape(self.url),
                         um._conn.escape(self.base),
                         um._conn.escape(self.index))

            um.cursor.execute(sql)
                                
            insert_id = um._conn.insert_id()

            return insert_id

    def get(self, id):
        """
        获取数据
        """
        with UsingMysql(log_time=True) as um:
            um.cursor.execute("SELECT * from `" + self.__table_name + "` WHERE `id`=" + id)
            return um.cursor.fetchone()

    def update(self):
        '''
        编辑数据
        '''
        with UsingMysql(log_time=True) as um:

            sql = (
                "UPDATE `"+self.__table_name +"` SET `did`=%s,`name`=%s,`title`=%s,`url`=%s,`base`=%s,`index`=%s"
                " WHERE `id`=%s"
            )
            sql = sql % (um._conn.escape(self.did),
                         um._conn.escape(self.name),
                         um._conn.escape(self.title),
                         um._conn.escape(self.url),
                         um._conn.escape(self.base),
                         um._conn.escape(self.index))

            um.cursor.execute(sql)
                                
            return um._conn.affected_rows
